package com.wujunshen.mongodb.page;

import java.util.List;
import lombok.Data;

/**
 * 分页对象
 *
 * @author frank woo(吴峻申) <br>
 * email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2020/2/7 5:33 下午 <br>
 */
@Data
public class Page<T> {
    /**
     * 总记录数
     */
    private long totalCount;
    /**
     * 总页数
     */
    private int pageCount;
    /**
     * 每页记录数
     */
    private int pageSize;
    /**
     * 当前页页码，从1开始
     */
    private int pageNo;
    /**
     * 上一页页码，为0时无上一页
     */
    private int prevPageNo;
    /**
     * 下一页页码，为0时无下一页
     */
    private int nextPageNo;
    /**
     * 本页数据集
     */
    private List<T> list;
    
    private String orderBy;
    private Class<?> clazz;
    /**
     * 最大显示记录数
     */
    private long maxSize;
    /**
     * 最后一页页码
     */
    private int endPageNo;
    
    public Page() {
        pageNo = 1;
        pageSize = 20;
    }
    
    public Page(int pageSize, int pageNo) {
        this.pageSize = pageSize;
        this.pageNo = (Math.max(pageNo, 1));
    }
    
    public void setPageSize(int pageSize) {
        if (this.pageSize != pageSize) {
            this.pageSize = pageSize;
            init();
        }
    }
    
    public void setList(List<T> list) {
        if (this.list != list) {
            this.list = list;
            init();
        }
    }
    
    public void init() {
        if (totalCount % this.pageSize == 0) {
            this.pageCount = (int) (totalCount / this.pageSize);
        } else {
            this.pageCount = (int) (totalCount / this.pageSize + 1);
        }
        this.endPageNo = this.pageCount;
        // 如果限制了最大记录数，最大页数只能以最大记录数计算
        if (this.maxSize > 0 && this.maxSize < this.totalCount) {
            this.endPageNo = (int) (this.maxSize / this.pageSize);
        }
        if (this.pageNo < 1) {
            this.pageNo = 1;
        } else if (this.endPageNo > 0 && this.pageNo > this.endPageNo) {
            this.pageNo = this.endPageNo;
        }
        this.prevPageNo = this.pageNo - 1;
        if (this.pageNo == this.endPageNo) {
            this.nextPageNo = 0;
        } else {
            this.nextPageNo = this.pageNo + 1;
        }
    }
    
    public void reset() {
        this.pageNo = 1;
        this.prevPageNo = 0;
        this.nextPageNo = 0;
        this.pageCount = 0;
        this.list = null;
        this.totalCount = 0;
    }
}
